package com.chuanyang.driverh.mainorder.adapter;

import android.content.Context;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chuanyang.driverh.R;
import com.chuanyang.driverh.bean.AssignGoodData;
import com.chuanyang.driverh.utils.LogUtils;
import com.chuanyang.driverh.utils.PrintUtil;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class AssignGoodDtailNewAdapter extends BaseAdapter {
    private LayoutInflater mLayoutInflater;
    int currentCount = 0;
    String currentCountString = "";

    private List<AssignGoodData.WaybillDetailsData> list;
    private Context context;
    private TextView tv_assigngooddetail_goodname;
    private TextView tv_assigngooddetail_standard;
    private TextView tv_assigngooddetail_totalweight;
    private EditText et_assigngooddetail_assignweight;
    private CharSequence mms;
    private String deleText;
    private String addText;
    private String lastText;
    private ViewHolder mViewHolder;


    public List<AssignGoodData.WaybillDetailsData> getList() {
        return list;
    }

    public AssignGoodDtailNewAdapter(Context context, List<AssignGoodData.WaybillDetailsData> list) {
        this.context = context;
        mLayoutInflater = LayoutInflater.from(context);
        this.list = list;
    }

    public void setList(List<AssignGoodData.WaybillDetailsData> list) {
        this.list = list;
        this.notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    //定义成员变量mTouchItemPosition,用来记录手指触摸的EditText的位置
    private int mTouchItemPosition = -1;

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            mViewHolder = new ViewHolder();
            convertView = mLayoutInflater.inflate(R.layout.order_item_assigngooddetail, null);
            mViewHolder.ll_assigngooddetail_div= (LinearLayout) convertView.findViewById(R.id.ll_assigngooddetail_div);
            mViewHolder.tv_assigngooddetail_goodname = (TextView) convertView.findViewById(R.id.tv_assigngooddetail_goodname);
            mViewHolder.tv_assigngooddetail_standard = (TextView) convertView.findViewById(R.id.tv_assigngooddetail_standard);
            mViewHolder.tv_assigngooddetail_totalweight = (TextView) convertView.findViewById(R.id.tv_assigngooddetail_totalweight);
            mViewHolder.et_assigngooddetail_assignweight = (EditText) convertView.findViewById(R.id.et_assigngooddetail_assignweight);
            mViewHolder.et_assigngooddetail_assignweight.setOnTouchListener(new View.OnTouchListener() {

                @Override
                public boolean onTouch(View view, MotionEvent event) {
                    //注意，此处必须使用getTag的方式，不能将position定义为final，写成mTouchItemPosition = position
                    mTouchItemPosition = (Integer) view.getTag();
                    //触摸的是EditText并且当前EditText可以滚动则将事件交给EditText处理；否则将事件交由其父类处理
                    if ((view.getId() == R.id.et_assigngooddetail_assignweight && canVerticalScroll((EditText) view))) {
                        view.getParent().requestDisallowInterceptTouchEvent(true);
                        if (event.getAction() == MotionEvent.ACTION_UP) {
                            view.getParent().requestDisallowInterceptTouchEvent(false);
                        }
                    }

                    return false;
                }
            });
            // 让ViewHolder持有一个TextWathcer，动态更新position来防治数据错乱；不能将position定义成final直接使用，必须动态更新
            mViewHolder.mTextWatcher = new MyTextWatcher();
            mViewHolder.et_assigngooddetail_assignweight.addTextChangedListener(mViewHolder.mTextWatcher);
            mViewHolder.updatePosition(position);
            convertView.setTag(mViewHolder);
        } else {
            mViewHolder = (ViewHolder) convertView.getTag();
            //动态更新TextWathcer的position
            mViewHolder.updatePosition(position);
        }
        AssignGoodData.WaybillDetailsData mitem = (AssignGoodData.WaybillDetailsData) list.get(position);
        InputFilter[] filters={new CashierInputFilter()};
        mViewHolder.et_assigngooddetail_assignweight.setFilters(filters);
        mViewHolder.tv_assigngooddetail_totalweight.setText(doubleTrans(mitem.getTotalWeight()));
        mViewHolder.tv_assigngooddetail_goodname.setText(mitem.getGoodName());
        mViewHolder.tv_assigngooddetail_standard.setText(mitem.getGoodsStandard());
        //设置值
        if (TextUtils.isEmpty(mitem.getDetailsWeight())) {
            mViewHolder.et_assigngooddetail_assignweight.setText("");
        }
        else {
            mViewHolder.et_assigngooddetail_assignweight.setText(mitem.getDetailsWeight());
            mViewHolder.tv_assigngooddetail_totalweight.setText(mitem.getTotalWeight() + "");

        }
        mViewHolder.et_assigngooddetail_assignweight.setTag(position);

        if (mTouchItemPosition == position) {
            mViewHolder.et_assigngooddetail_assignweight.requestFocus();
            mViewHolder.et_assigngooddetail_assignweight.setSelection(mViewHolder.et_assigngooddetail_assignweight.getText().length());
        } else {
            mViewHolder.et_assigngooddetail_assignweight.clearFocus();
        }


        return convertView;
    }

    class ViewHolder {
        TextView tv_assigngooddetail_goodname;
        TextView tv_assigngooddetail_standard;
        TextView tv_assigngooddetail_totalweight;
        EditText et_assigngooddetail_assignweight;
        LinearLayout ll_assigngooddetail_div;
        MyTextWatcher mTextWatcher;

        //动态更新TextWathcer的position
        public void updatePosition(int position) {
            mTextWatcher.updatePosition(position);
        }
    }

    class MyTextWatcher implements TextWatcher {
        //由于TextWatcher的afterTextChanged中拿不到对应的position值，所以自己创建一个子类
        private int mPosition;

        public void updatePosition(int position) {
            mPosition = position;
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            currentCount = s.toString().length();
            currentCountString=s.toString();



        }

        @Override
        public void afterTextChanged(Editable s) {
            AssignGoodData.WaybillDetailsData mitem = list.get(mPosition);
            try {
                if (TextUtils.isEmpty(s))
                {
                    mitem.setDetailsWeight(null);
                    // tv_assigngooddetail_totalweight.setText(doubleTrans(mitem.getTotalWeight()));

                }
                else {
//                    if (mitem != null && (mitem.getTotalWeight() - Double.parseDouble(String.valueOf(s)) < 0))
//                    {
//                        if(currentCount>s.toString().length() )  //在删除
//                        {
//
//                        }
//                        else
//                        {
//                            ToastUtils.showShort(context, "派单重量不能大于剩余货物重量");
//                            mitem.setDetailsWeight(currentCountString);//添加
//                            notifyDataSetChanged();
//                            LogUtils.e("notifyDataSetChanged",currentCountString+"-------------------");
//
//                        }
//                    }
//                    else
//                    {
                        mitem.setDetailsWeight(String.valueOf(s));
                        LogUtils.e("afterTextChanged", s.toString() + "----");
                 //   }


                }
                list.set(mPosition, mitem);

            } catch (Exception e) {
                PrintUtil.toast(context, "您输入了非法参数");
            }
        }
    }

    public static String doubleTrans(double d) {
        if (Math.round(d) - d == 0) {
            return String.valueOf((long) d);
        }
        return String.valueOf(d);
    }


        /**
     * 输入过滤器
     */
    public class CashierInputFilter implements InputFilter {
        Pattern mPattern;
        //输入的最大金额
        private static final int MAX_VALUE = Integer.MAX_VALUE;
        //小数点后的位数
        private static final int POINTER_LENGTH = 3;
        private static final String POINTER = ".";
        private static final String ZERO = "0";
        public CashierInputFilter() {
            mPattern = Pattern.compile("([0-9]|\\.)*");
        }
        /**
         * @param source    新输入的字符串
         * @param start     新输入的字符串起始下标，一般为0
         * @param end       新输入的字符串终点下标，一般为source长度-1
         * @param dest      输入之前文本框内容
         * @param dstart    原内容起始坐标，一般为0
         * @param dend      原内容终点坐标，一般为dest长度-1
         * @return          输入内容
         */
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            String sourceText = source.toString();
            String destText = dest.toString();
            //验证删除等按键
            if (TextUtils.isEmpty(sourceText)) {
                return "";
            }
            Matcher matcher = mPattern.matcher(source);
            //已经输入小数点的情况下，只能输入数字
            if(destText.contains(POINTER)) {
                if (!matcher.matches()) {
                    return "";
                } else {
                    if (POINTER.equals(source)) {  //只能输入一个小数点
                        return "";
                    }
                }
                //验证小数点精度，保证小数点后只能输入1位
                int index = destText.indexOf(POINTER);
                int length = dend - index;
                if (length > POINTER_LENGTH) {
                    return dest.subSequence(dstart, dend);
                }
            } else {
                //没有输入小数点的情况下，只能输入小数点和数字，但首位不能输入小数点和0
                if (!matcher.matches()) {
                    return "";
                } else {
                    if ((POINTER.equals(source)) && TextUtils.isEmpty(destText)) {
                        return "";
                    }
                    //如果首位为“0”，则只能再输“.”
                    if(ZERO.equals(destText)){
                        if(!POINTER.equals(sourceText)){
                            return "";
                        }
                    }
                }
            }
            //验证输入金额的大小
            double sumText = Double.parseDouble(destText + sourceText);
            if (sumText > MAX_VALUE) {
                return dest.subSequence(dstart, dend);
            }
            return dest.subSequence(dstart, dend) + sourceText;
        }
    }

    /**
     * EditText竖直方向是否可以滚动
     *
     * @param editText 需要判断的EditText
     * @return true：可以滚动 false：不可以滚动
     */
    private boolean canVerticalScroll(EditText editText) {
        //滚动的距离
        int scrollY = editText.getScrollY();
        //控件内容的总高度
        int scrollRange = editText.getLayout().getHeight();
        //控件实际显示的高度
        int scrollExtent = editText.getHeight() - editText.getCompoundPaddingTop() - editText.getCompoundPaddingBottom();
        //控件内容总高度与实际显示高度的差值
        int scrollDifference = scrollRange - scrollExtent;

        if (scrollDifference == 0) {
            return false;
        }

        return (scrollY > 0) || (scrollY < scrollDifference - 1);
    }


}

